package com.sd365.permission.centre.service.impl;

import com.sd365.permission.centre.dao.mapper.ResourceMapper;
import com.sd365.permission.centre.dao.mapper.RoleMapper;
import com.sd365.permission.centre.dao.mapper.TenantMapper;
import com.sd365.permission.centre.dao.mapper.UserMapper;
import com.sd365.permission.centre.entity.Resource;
import com.sd365.permission.centre.entity.Role;
import com.sd365.permission.centre.entity.User;
import com.sd365.permission.centre.pojo.vo.ResourceVO;
import com.sd365.permission.centre.service.LoginService;
import com.sd365.permission.centre.service.MenuService;
import com.sd365.permission.centre.service.UserOnlineService;
import com.sd365.permission.centre.service.util.Md5Utils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Class LoginServiceImpl
 * @Description  实现登录认证和用户信息获取功能
 * @Author JiaoBingjie
 * @Date 2020/12/11  17:07
 * @version 1.0.0
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    /**
     * 用于操作user表验证账号密码
     */
    @Autowired
    private UserMapper userMapper;
    /**
     *  查询租户相关信息
     */
    @Autowired
    private TenantMapper tenantMapper;
    /**
     * 查询角色相关信息
     */
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 查询资源相关信息针对resource表
     */
    @Autowired
    private ResourceMapper resourceMapper;
    /**
     * 主要用于构建菜单
     */
    @Autowired
    private MenuService menuService;

    /**
     *  引入做登录状态更新和登录进入插入
     */
    @Autowired
    private UserOnlineService userOnlineService;



    @Override
    public int verification(String code, String password, String account) {
        User user=userMapper.selectNameByCodePassword(code,password);
        if(null!=user){
            // 可能存在租户输入错误的情况
            Long tenantId = tenantMapper.selectTenantIdByTenantAccount(account);
            if(tenantId==null || !tenantId.equals(user.getTenantId())){
                return LOGIN_VERIFY_CODE_TENANT_ERR;
            }else{
                return LOGIN_VERIFY_CODE_SUCCESS;
            }
        }else{ // 账号或者或者密码已经错误
            return LOGIN_VERIFY_CODE_CODE_OR_PASSWORD_ERR;
        }
    }

    @Override
    public User getUserInfo(String code, String account) {
        Long tenantId = tenantMapper.selectTenantIdByTenantAccount(account);
        User user = userMapper.selectUserByCodeTenantid(code, tenantId);
        return user;
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        List<Role> roles = roleMapper.selectRolesByUserId(userId);
        return roles;
    }

    @Override
    public List<ResourceVO> getResourceVO(List<Role> roles) {
        /**
         * 根据角色取得所有的角色id加入列表
         */
        List<Long> roleIds = new ArrayList<>();
        Iterator<Role> it = roles.iterator();
        while(it.hasNext()) {
            roleIds.add(it.next().getId());
        }
        // 批量查询取得角色所包含的所有的资源
        List<Resource> resources=resourceMapper.getResourceByRoleId(roleIds);
        // 这个service按规范应该是dto出去的 这个代码有待优化 另外这个功能也很奇怪
        List<ResourceVO> resourceVOs = menuService.buildMenu(resources);
        return resourceVOs;
    }

    @Override
    public Boolean updateUserOnlineStatus(Long userId,byte status) {
        if (userId == null){
            return false;
        }
        return userMapper.updateUserOnlineStatus(userId,status) > 0;
    }


    @Override
    public LoginUserDTO auth(String code, String password, String account) {

        LoginUserDTO loginUserDTO=new LoginUserDTO();
        /**
         * 1 认证通过返回带权限的UserVO
         * 2 插入登录记录并且更新登录状态
         */
        int result = verification(code, Md5Utils.digestHex(password), account);
        if (LoginServiceImpl.LOGIN_VERIFY_CODE_SUCCESS==result) {
            User user = getUserInfo(code, account);

            List<Long> roleIds = new LinkedList<>();
            List<Role> roles = getRolesByUserId(user.getId());

            for (Role role : roles) {
                roleIds.add(role.getId());
            }

            loginUserDTO.setId(user.getId());
            loginUserDTO.setName(user.getName());
            loginUserDTO.setRoleIds(roleIds);
            loginUserDTO.setTenantId(user.getTenantId());
            loginUserDTO.setOrgId(user.getOrgId());
            loginUserDTO.setCompanyId(user.getCompanyId());
            loginUserDTO.setResultCode(result);
            // 用户登陆判断
            if (user.getStatus().intValue() == 1 && user.getStatus().intValue() != 3) {
                // 登陆成功修改status值
                updateUserOnlineStatus(user.getId(), (byte) 3);
            }
            // 保存登陆信息
            userOnlineService.saveLoginInfo(user);
        } else {
            loginUserDTO.setResultCode(result);
        }
        return loginUserDTO;
    }
}
